package com.example.day9_sqlite;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

public class SqlFragment extends Fragment {
    MusicAdapter musicAdapter;
    private GridView gv;


    public SqlFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_sql, container, false);
        initView(inflate);
        musicAdapter = new MusicAdapter();
        gv.setAdapter(musicAdapter);

        //点击删除数据库中数据
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //先删数据库
                MusicDao.getInstance(getContext()).delete(musicAdapter.getItem(position).getName());
                //再删除页面
                musicAdapter.remove(position);
            }
        });

        return inflate;
    }

    private void initView(View inflate) {
        gv = (GridView) inflate.findViewById(R.id.gv);
    }

    @Override
    public void onResume() {
        super.onResume();
        List<MusicEntity.DataBean> beanList = MusicDao.getInstance(getContext()).query("", "");
        musicAdapter.addAll(beanList);
    }
}